/*
 * Copyright (c) 2011 by Konstantin Pavlov.
 */
package gwtlx.util.client;

import com.google.gwt.core.client.GWT;
import com.google.gwt.http.client.*;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONParser;
import com.google.gwt.json.client.JSONValue;

/**
 * JsonServiceUtil is a helper class to commumicate with remote JSON service.
 *
 * @author Konstantin Pavlov
 * @version $LastChangedRevision: 20 $
 * @since 15.12.10
 */
@SuppressWarnings({"UnusedDeclaration"})
public abstract class JsonServiceUtil {

    /**
     * Sends POST request to specifid URI and calls provided callback when finished.
     *
     * @param uri      Service endpoint
     * @param data     A JSON object to send
     * @param callback A callback to invoke
     */
    public static void sendRequest(String uri, JSONObject data, final JSONCallback callback) {
        RequestBuilder builder = new RequestBuilder(RequestBuilder.POST, uri);
        String payload;
        if (data != null) {
            payload = data.toString();
        } else {
            payload = "";
        }
        builder.setHeader("Content-type", "application/x-www-form-urlencoded");
        try {
            builder.sendRequest(payload, new RequestCallback() {

                @Override
                public void onResponseReceived(Request request, Response response) {
                    if (response.getStatusCode() == 200) {
                        final JSONValue jsonValue = JSONParser.parseStrict(response.getText());
                        callback.onSuccess(jsonValue);
                    } else {
                        callback.onFailure(response.getStatusCode(), response.getStatusText());
                    }
                }

                @Override
                public void onError(Request request, Throwable exception) {
                    callback.onError(exception);

                }
            });
        } catch (RequestException e) {
            GWT.log("Error while sending JSON request", e);
            callback.onError(e);
        }
    }


    /**
     * A callback class used for JSON service communication
     *
     * @see JsonServiceUtil#sendRequest(String, com.google.gwt.json.client.JSONObject, gwtlx.util.client.JsonServiceUtil.JSONCallback)
     */
    public static class JSONCallback {

        /**
         * Called when service has returned code other than 200 (OK)
         *
         * @param statusCode server status code <> 200
         * @param statusText server status text
         */
        public void onFailure(int statusCode, String statusText) {
            GWT.log("Error " + statusCode + ": " + statusText);
        }

        /**
         * Called when error has happened when sending or receiving data to/from server.
         *
         * @param exception an exception was thrown
         */
        public void onError(Throwable exception) {
            GWT.log(exception.getMessage(), exception);
        }

        /**
         * Is called when some data is received from service
         *
         * @param jsonValue a received JSON object
         */
        public void onSuccess(JSONValue jsonValue) {
            // noop
        }
    }
}


